package org.dong.Controller;

import com.alibaba.fastjson.JSON;
import org.dong.Dao.UserDao;
import org.dong.Dao.UserDaoImpl;
import org.dong.Pojo.Dto;
import org.dong.Pojo.HttpRequest;
import org.dong.Pojo.HttpResponse;
import org.dong.Tool.Data;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class RegController implements ServerLet {

    @Override
    public void server(HttpRequest request, OutputStream os) {
        Dto dto = new Dto();
        String msg = "ok";
        //查找数据中是否存在此用户

        String[] list = request.getRequestData().split("&");

        //获取用户名
        String username = URLDecoder.decode(list[0].split("=")[1]);
        String account = list[1].split("=")[1];
        String phone = list[2].split("=")[1];
        String password = list[3].split("=")[1];
        String check_password = list[4].split("=")[1];

        UserDao userDao = new UserDaoImpl();
        Map<String,String> map = new HashMap<>();
        map.put("username",username);
        map.put("account",account);
        map.put("password",password);
        map.put("phone",phone);
        //查找账号是否已存在
        if(userDao.checkAccount(map)){
            dto.setErrMsg("账号已存在");
            dto.setStatusCode(2001);
        }else{

            //注册账号
            if(userDao.reg(map)){

                dto.setErrMsg("账号注册成功");
                dto.setStatusCode(2000);
            }
        }

        msg = JSON.toJSONString(dto);
        new HttpResponse(os,request.getUrl(),msg);
    }
}
